import request from './useRequests';
import { userinfo } from '@/stores/counter';
import { ElMessage } from 'element-plus';
import getStatus from '@/api/getStatus';

export default function usesignup() {
  const user = userinfo();
  const { status } = getStatus();

  async function codeAuth(email: string, type: string) {
    if (!email) {
      ElMessage({
        showClose: true,
        message: '请输入验证邮箱！',
        type: 'error',
      });
      return 0;
    }

    try {
      const res = await request({
        method: 'post',
        url: `auth/getEmailCode`,
        params: {
          email: email,
          type: type,
        },
      });
      if (res.status) {
        ElMessage({
          showClose: true,
          message: '发送成功',
          type: 'success',
        });
      }
    } catch (err: any) {
      ElMessage({
        showClose: true,
        message: '发送失败',
        type: 'error',
      });
    }
  }
  async function signup() {
    try {
      const signupinfo = user.signupInfo;
      const res = await request.post('/auth/register', {
        phone: signupinfo.telephone,
        email: signupinfo.email,
        username: signupinfo.username,
        password: signupinfo.password,
        avator: signupinfo.avator,
        code: signupinfo.code,
        sex: signupinfo.sex,
      });

      if (res.data.status == true) {
        ElMessage({
          showClose: true,
          message: '注册成功',
          type: 'success',
        });
        signupinfo.telephone = '';
        signupinfo.email = '';
        signupinfo.username = '';
        signupinfo.password = '';
        signupinfo.password2 = '';
        signupinfo.avator = '';
        signupinfo.code = '';
        signupinfo.sex = '';
      } else {
        ElMessage({
          showClose: true,
          message: `${res.data.message}`,
          type: 'error',
        });
      }
    } catch (err: any) {
      //alert(err)
    }
  }

  return {
    signup,
    codeAuth,
  };
}
